/*
 * 版权所有：杭州领域向尚科技有限公司
 * 地址：浙江省杭州市滨江区滨安路688号天和高科技产业园5-2311
 *
 * (c) Copyright Hangzhou  Area Up Technology Co., Ltd.
 */

package org.elanfox.intellicommunity.common.resource.impl;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.FileObject;
import org.elanfox.intellicommunity.common.resource.StaticResourceService;
import org.elanfox.intellicommunity.common.resource.base.VfsFileSystemResource;
import org.elanfox.intellicommunity.common.resource.vfs.VfsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * 基于VFS的静态资源处理
 * 生产环境用该服务
 *
 * @author allan
 * @date 12/11/2017
 */
@Service("resourceService")
public class VfsResourceServiceImpl implements StaticResourceService {
    private static final Log log = LogFactory.getLog(VfsResourceServiceImpl.class);

    /**
     * 资源前缀
     * 以"/"结尾
     */
    private String uriPrefix;
    /**
     * 文件位置
     * 以"/"结尾
     */
    private String fileHome;

    @Autowired
    private VfsHelper vfsHelper;

    @Autowired
    public VfsResourceServiceImpl(Environment environment) throws URISyntaxException {
        String uriPrefix = environment.getProperty("resourceUri", "http://192.168.31.128/image/");
        if (StringUtils.isEmpty(uriPrefix)) {
            throw new IllegalStateException("未设置resourceUri");
        }
        String fileHome = environment.getProperty("resourceHome", "/home/file/");
        if (StringUtils.isEmpty(fileHome)) {
            throw new IllegalStateException("未设置resourceHome");
        }
        this.uriPrefix = uriPrefix;
        this.fileHome = fileHome;
    }

    @Override
    public Resource upload(String path, InputStream data) throws IOException, URISyntaxException {
        vfsHelper.saveLocal(fileHome + path, data);
        return get(path);
    }

    @Override
    public Resource get(String path) throws URISyntaxException {
        return new VfsFileSystemResource(vfsHelper, fileHome, path, new URI(uriPrefix + path));
    }

    @Override
    public void delete(String path) throws IOException {
        if (StringUtils.isEmpty(path)) {
            return;
        }

        vfsHelper.handle(fileHome + path, FileObject::delete);
    }
}
